<!--
 * @Description: 单品打折功能
 * @Author: duan_shuangjun 丶
 * @Date: 2025-09-10 17:30:30
-->
<template>
  <custom-dialog v-model:visible="dialogVisible" top="8vh" curent-class="discount-food-dialog">
    <div class="dialog-content">
      <div class="title">菜品打折</div>
      <div class="description" v-if="selectedFood">
        <div class="name">{{ selectedFood.name }}</div>
      </div>
      <div class="scroll-content">
        <div class="scroll-list">
          <div
            class="scroll-item"
            :class="{ 'scroll-item-active': selectActiveIndex === index }"
            v-for="(item, index) in tabList"
            :key="item.name + index"
            @click="handleSelectDiscount(index, item.number)"
          >
            {{ item.name }}
          </div>
        </div>
      </div>
      <div class="form-box">
        <div class="form-item">
          <div class="desc">折扣值</div>
          <div class="dialog-input">
            <input
              class="input"
              v-model.trim="discountValue"
              type="text"
              @input="handleInputDiscount"
              placeholder="请输入折扣值"
            />
            <img
              class="image"
              src="@/assets/images/home/input-clear.png"
              alt=""
              @click="handleClearInput"
              v-if="discountValue"
            />
          </div>
        </div>
      </div>

      <!-- 数字键盘（参考 FullOrderDiscountDialog.vue） -->
      <NumberKeyboard
        v-model:keyword="discountValue"
        :showRadixPoint="true"
        :isFirstZero="false"
        :maxStrLimit="3"
        :loading="loading"
        @onInputKeyboard="onInputKeyboard"
        @onCancel="handleClearInput"
        @onConfirm="handleConfirm"
      />

      <div class="btn-box">
        <div class="desc">
          单价：￥{{ currentFoodPrice }}
          <span v-if="discountPrice">，折扣价：￥{{ discountPrice }}</span>
        </div>
        <el-button class="cancel-btn" @click="handleCancel" :loading="loading">撤销打折</el-button>
      </div>
    </div>
  </custom-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { orderFoodDiscountEdit } from '@/api/food'
import CustomDialog from '@/components/CustomDialog/Index.vue'
import { ElButton } from 'element-plus'
import NumberKeyboard from '@/components/NumberKeyboard/Index.vue'

interface Props {
  deskDetail: any
  selectFoodActiveIndex: number
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'refreshData'): void
  (e: 'refreshDesk'): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  deskDetail: () => ({}),
  selectFoodActiveIndex: -1
})

const emit = defineEmits<Emits>()

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: val => emit('update:modelValue', val)
})

// 选中的菜品
const selectedFood = ref<any>(null)
// 加载状态
const loading = ref(false)
// 折扣值
const discountValue = ref('')
// 折扣价（字符串保留两位小数，便于直接展示）
const discountPrice = ref<string | null>(null)
// 折扣值列表
const tabList = ref([
  { name: '八折', number: '8' },
  { name: '九折', number: '9' },
  { name: '七折', number: '7' },
  { name: '五折', number: '5' }
])
// 选中对应折扣的索引
const selectActiveIndex = ref(-1)

// 当前菜品的价格
const currentFoodPrice = computed(() => {
  if (!selectedFood.value) return '0.00'

  // 计算会员价格
  if (props.deskDetail?.is_vip === 1) {
    return (
      parseFloat(selectedFood.value.num) * parseFloat(selectedFood.value.member_price || 0) || 0
    ).toFixed(2)
  } else {
    return (
      parseFloat(selectedFood.value.num) * parseFloat(selectedFood.value.price || 0) || 0
    ).toFixed(2)
  }
})

// 清空输入框
const handleClearInput = () => {
  discountValue.value = ''
  discountPrice.value = null
  selectActiveIndex.value = -1
}

// 选中对应的折扣
const handleSelectDiscount = (index: number, number: string) => {
  selectActiveIndex.value = index
  discountValue.value = number

  // 计算折扣价
  calculateDiscountPrice(number)
}

// 处理折扣输入
const handleInputDiscount = (event: Event) => {
  const target = event.target as HTMLInputElement
  // 只允许输入数字和小数点
  let value = target.value.replace(/[^\d.]/g, '')

  // 如果有小数点，只保留一位小数点
  if (value.indexOf('.') !== -1) {
    const parts = value.split('.')
    if (parts.length > 2) {
      value = parts[0] + '.' + parts[1]
    }
  }

  // 限制最大值为10（不打折）
  if (parseFloat(value) > 10) {
    value = '10'
  }

  discountValue.value = value

  // 计算折扣价
  calculateDiscountPrice(value)
}

// 数字键盘输入
const onInputKeyboard = (val: string) => {
  discountValue.value = val
  calculateDiscountPrice(val)
}

// 计算折扣价
const calculateDiscountPrice = (value: string) => {
  if (!value || value === '.' || value === '0') {
    discountPrice.value = null
    return
  }

  const discountVal = parseFloat(value) / 10
  if (discountVal && selectedFood.value) {
    discountPrice.value = (discountVal * parseFloat(currentFoodPrice.value)).toFixed(2)
  } else {
    discountPrice.value = null
  }
}

// 重置数据
const resetData = () => {
  selectActiveIndex.value = -1
  discountValue.value = ''
  discountPrice.value = null
}

// 监听对话框打开状态
watch(
  () => dialogVisible.value,
  val => {
    if (val) {
      // 获取选中的菜品信息
      selectedFood.value = props.deskDetail.foodList?.[props.selectFoodActiveIndex]
      // 重置数据
      resetData()
    }
  }
)

// 确认打折处理
const handleConfirm = async () => {
  if (!discountValue.value) {
    ElMessage.warning('折扣值不能为空')
    return
  }

  if (parseFloat(discountValue.value) <= 0) {
    ElMessage.warning('折扣值不能小于或等于0')
    return
  }

  if (parseFloat(discountValue.value) > 10) {
    ElMessage.warning('折扣值不能大于10')
    return
  }

  if (loading.value) return

  try {
    loading.value = true

    const params = {
      id: selectedFood.value.id,
      discount: discountValue.value
    }

    const res = await orderFoodDiscountEdit(params)
    if (res.status === 200) {
      ElMessage.success(res.data?.message || '打折成功')
      dialogVisible.value = false
      emit('refreshData')
      emit('refreshDesk')
    } else {
      ElMessage.error(res.data?.message || '打折失败')
    }
  } catch (error) {
    console.error('打折失败:', error)
    ElMessage.error('打折失败')
  } finally {
    loading.value = false
  }
}

// 撤销打折处理
const handleCancel = async () => {
  if (loading.value) return

  try {
    loading.value = true

    const params = {
      id: selectedFood.value.id,
      discount: 10 // 10表示不打折
    }

    const res = await orderFoodDiscountEdit(params)
    if (res.status === 200) {
      ElMessage.success(res.data?.message || '撤销打折成功')
      dialogVisible.value = false
      emit('refreshData')
      emit('refreshDesk')
    } else {
      ElMessage.error(res.data?.message || '撤销打折失败')
    }
  } catch (error) {
    console.error('撤销打折失败:', error)
    ElMessage.error('撤销打折失败')
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.dialog-content {
  .title {
    font-size: 20px;
    font-family:
      PingFang SC,
      PingFang SC-Bold;
    font-weight: 700;
    text-align: center;
    color: #353535;
  }

  .description {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 16px;
    font-size: 16px;
    font-family:
      PingFang SC,
      PingFang SC-Regular;
    font-weight: 400;
    text-align: center;
    color: #353535;

    .name {
      font-size: 18px;
      font-weight: 700;
    }
  }

  .scroll-content {
    background: #f4f4f4;
    height: 120px;
    box-sizing: border-box;
    padding: 20px 0;
    overflow-y: auto;
    margin-top: 20px;

    .title {
      position: relative;
      z-index: 2;
      font-size: 16px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      text-align: left;
      color: #333333;
      padding: 0px 40px;
    }

    .scroll-list {
      width: 556px;
      position: relative;
      z-index: 2;
      padding: 0px 40px;
      display: flex;
      align-items: center;
      gap: 20px;
      flex-wrap: wrap;

      .scroll-item {
        min-width: 120px;
        height: 48px;
        line-height: 48px;
        background: #ffffff;
        border: 1px solid #d2d2d2;
        border-radius: 12px;
        font-size: 14px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        text-align: center;
        color: #333333;
        margin-top: 20px;
        cursor: pointer;
      }

      .scroll-item-active {
        border-color: #7c0a03 !important;
        color: #7c0a03 !important;
      }
    }
  }

  //滚动条整体的大小
  .scroll-content::-webkit-scrollbar {
    width: 6px;
    height: 0;
  }

  //滚动条里滑动的滑块
  .scroll-content::-webkit-scrollbar-thumb {
    height: 90px;
    background: #d2d2d2;
    border-radius: 3px;
  }

  //滚动条底层样式
  .scroll-content::-webkit-scrollbar-track {
    display: none;
  }

  .desc {
    font-size: 16px;
    font-family:
      PingFang SC,
      PingFang SC-Regular;
    font-weight: 400;
    color: #333333;
  }

  .form-box {
    padding: 30px 60px;

    .form-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 20px;

      .dialog-input {
        width: 420px;
        height: 48px;
        background: #ffffff;
        border: 1px solid #d2d2d2;
        border-radius: 12px;
        box-sizing: border-box;
        padding: 0 20px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .input {
          width: 400px;
          font-size: 14px;
          font-family:
            PingFang SC,
            PingFang SC-Regular;
          font-weight: 400;
          text-align: left;
          color: #333333;
          outline: none;
          border: none;
        }

        .image {
          flex-shrink: 0;
          width: 24px;
          height: 24px;
          cursor: pointer;
        }
      }
    }
  }

  .discount-info {
    padding: 0 40px;
    margin-top: 20px;

    .desc {
      font-size: 16px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      color: #333333;
    }
  }

  .btn-box {
    padding: 30px 60px 0 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .cancel-btn {
      width: 190px;
      height: 52px;
      border: 1px solid #d2d2d2;
      border-radius: 12px;
      font-size: 18px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      text-align: center;
      color: #353535;
      line-height: 52px;
      cursor: pointer;
    }

    .confirm-btn {
      width: 190px;
      height: 52px;
      background: #7c0a03;
      border-radius: 12px;
      font-size: 18px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      text-align: center;
      color: #ffffff;
      line-height: 52px;
      cursor: pointer;

      &.loading {
        opacity: 0.7;
        cursor: not-allowed;
      }
    }
  }
}
</style>
<style>
.discount-food-dialog {
  padding: 50px 0px !important;
  max-height: unset !important;
}
</style>
